﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;



namespace MyPSDALayer
{
    public class FileFormatAttribute : ValidationAttribute, IClientValidatable
    {
        public string Format { get; set; }
        public FileFormatAttribute(string format)
            : base("文件格式不正确")
        {
            Format = format;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                var arr = value.ToString().Split('.');
                string fileFormat = arr[arr.Length - 1];
                if (!this.Format.ToLower().Contains(fileFormat.ToLower()))
                {
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
                }
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("fileformat", Format);
            rule.ValidationType = "validatefileformat";
            yield return rule;
        }
    }
}